package com.example.demo.quartz;

import com.example.demo.utils.CalendarUtils;
import org.apache.commons.lang3.StringUtils;
import org.quartz.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Objects;

@Component
public class QuartzManager {

    @Autowired(required = false)
    private Scheduler scheduler;

    /**
     * 开始执行任务
     *
     * @throws SchedulerException
     */
    public void startJob(String jobName, String jobGroup, String cron) throws SchedulerException {
        //查到信息进行修改操作  查不到进行新增操作
        String jobInfo = getJobInfo(jobName, jobGroup);
        System.out.println("触发定时任务");
        if (StringUtils.isBlank(jobInfo)) {
            startJob(scheduler, jobName, jobGroup, formatDateByPattern(CalendarUtils.format(cron, CalendarUtils.DATETIME_FORMAT)));
        } else {
            modifyJob(jobName, jobGroup, cron);
        }
    }

    /**
     * 获取Job信息
     */
    public String getJobInfo(String name, String group) throws SchedulerException {
        TriggerKey triggerKey = new TriggerKey(name, group);
        CronTrigger cronTrigger = (CronTrigger) scheduler.getTrigger(triggerKey);
        if (null == cronTrigger) {
            return null;
        }
        return String.format("time:%s,state:%s", cronTrigger.getCronExpression(),
                scheduler.getTriggerState(triggerKey).name());

    }

    /**
     * 修改某个任务的执行时间
     */
    public boolean modifyJob(String name, String group, String time) throws SchedulerException {
        String newTime = formatDateByPattern(CalendarUtils.format(time, CalendarUtils.DATETIME_FORMAT));
        Date date = null;
        TriggerKey triggerKey = new TriggerKey(name, group);
        CronTrigger cronTrigger = (CronTrigger) scheduler.getTrigger(triggerKey);
        String oldTime = cronTrigger.getCronExpression();
        if (!oldTime.equalsIgnoreCase(newTime)) {
            CronScheduleBuilder cronScheduleBuilder = CronScheduleBuilder.cronSchedule(newTime);
            CronTrigger trigger = TriggerBuilder.newTrigger().withIdentity(name, group)
                    .withSchedule(cronScheduleBuilder).build();
            date = scheduler.rescheduleJob(triggerKey, trigger);
        }
        return date != null;
    }


    /**
     * 删除某个任务
     */
    public void deleteJob(String name, String group) throws SchedulerException {
        JobKey jobKey = new JobKey(name, group);
        JobDetail jobDetail = scheduler.getJobDetail(jobKey);
        if (jobDetail == null)
            return;
        scheduler.deleteJob(jobKey);
    }

    private void startJob(Scheduler scheduler, String jobName, String jobGroup, String cron) throws SchedulerException {

        JobDetail jobDetail = JobBuilder.newJob(SchedulerQuartzJob.class).withIdentity(jobName, jobGroup).build();
        CronScheduleBuilder cronScheduleBuilder = CronScheduleBuilder.cronSchedule(cron);
        CronTrigger cronTrigger = TriggerBuilder.newTrigger().withIdentity(jobName, jobGroup)
                .withSchedule(cronScheduleBuilder).build();
        scheduler.scheduleJob(jobDetail, cronTrigger);
    }


    private static final SimpleDateFormat sdf = new SimpleDateFormat("ss mm HH dd MM ?");

    /***
     * 日期转换cron表达式
     */
    public static String formatDateByPattern(Date date) {
        String formatTimeStr = null;
        if (Objects.nonNull(date)) {
            formatTimeStr = sdf.format(date);
        }
        return formatTimeStr;
    }

}
